const Like = require('../models/likeModel');

class LikeController {
    static async toggleLike(req, res) {
        try {
            const newsId = req.params.newsId;
            const userId = req.user.userId || req.user.user_id; 

            
            const alreadyLiked = await Like.exists({ news_id: newsId, user_id: userId });

            if (alreadyLiked) {
              
                await Like.delete({ news_id: newsId, user_id: userId });
                res.json({
                    success: true,
                    message: 'News unliked successfully',
                    liked: false
                });
            } else {
                // Like the news
                await Like.create({ news_id: newsId, user_id: userId });
                res.json({
                    success: true,
                    message: 'News liked successfully',
                    liked: true
                });
            }
        } catch (error) {
            console.error('Error in toggleLike:', error);
            res.status(500).json({
                success: false,
                message: 'Error toggling like',
                error: error.message
            });
        }
    }

    static async unlike(req, res) {
        try {
            const newsId = req.params.newsId;
            const userId = req.user.userId || req.user.user_id;

            const deleted = await Like.delete({ news_id: newsId, user_id: userId });
            
            if (deleted) {
                res.json({
                    success: true,
                    message: 'News unliked successfully',
                    liked: false
                });
            } else {
                res.status(404).json({
                    success: false,
                    message: 'Like not found'
                });
            }
        } catch (error) {
            console.error('Error in unlike:', error);
            res.status(500).json({
                success: false,
                message: 'Error unliking news',
                error: error.message
            });
        }
    }

    static async getLikesCount(req, res) {
        try {
            const newsId = req.params.newsId;
            const count = await Like.getNewsLikesCount(newsId);
            res.json({
                success: true,
                count
            });
        } catch (error) {
            console.error('Error in getLikesCount:', error);
            res.status(500).json({
                success: false,
                message: 'Error getting likes count',
                error: error.message
            });
        }
    }
}

module.exports = LikeController; 